package com.android.djlmapp.activity.kaika;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.djlmapp.R;
import com.android.djlmapp.application.MyApplication;
import com.android.djlmapp.http.GlobalUrls;
import com.android.djlmapp.model.kaika.SignImageInfo;
import com.android.djlmapp.tools.global.ToastUtils;
import com.android.readcard.dialog.MyUsualyDialog;
import com.android.readcard.utils.ImageTools;
import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * 横屏显示,沉浸式状态栏
 */
@RuntimePermissions
public class QianMingActivity extends AppCompatActivity {

    @BindView(R.id.fm_sign)
    FrameLayout fmSign;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.btn_cx_sign)
    TextView btnCxSign;
    @BindView(R.id.btn_ok_sign)
    TextView btnOkSign;
    @BindView(R.id.activity_heng_xiang_sign)
    RelativeLayout activityHengXiangSign;

    private MyUsualyDialog dialog;
    private PaintView mView;
    // 标记是否签名
    private String flag = "0";
    private String path = "";

    /**
     * 签名上传成功结果值
     */
    public static final String UPLOAD_IMG_SUCCESS_RESULT_DATA = "UPLOAD_IMG_SUCCESS_RESULT_DATA";
    private String homeUrl = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_heng_xiang_sign);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        ButterKnife.bind(this);

        QianMingActivityPermissionsDispatcher.NeedsWithCheck(this);
        initView();
        initData();
        // 沉浸式
        initImmersionBar();
    }

    private void initView() {
        dialog = new MyUsualyDialog(QianMingActivity.this, R.layout.wait_item);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                btnOkSign.setEnabled(true);
            }
        });
    }

    private void initData() {
        Intent intent = getIntent();
        homeUrl = intent.getStringExtra("SIGN_URL");

        // 签名
        mView = new PaintView(this);
        fmSign.addView(mView);
        mView.requestFocus();
    }

    /**
     * 签名
     */
    class PaintView extends View {
        private Paint paint;
        private Canvas cacheCanvas;
        private Bitmap cachebBitmap;
        private Path path;

        /**
         * 返回签名bitmap
         */
        public Bitmap getCachebBitmap() {
            return cachebBitmap;
        }

        public PaintView(Context context) {
            super(context);
            init();
        }

        private void init() {
            paint = new Paint();
            paint.setAntiAlias(true);
            paint.setFakeBoldText(true);
            paint.setStrokeWidth(10.0f);
            paint.setStyle(Paint.Style.STROKE);
            paint.setColor(Color.BLACK);
            path = new Path();
            cachebBitmap = Bitmap.createBitmap(10, 10, Bitmap.Config.ARGB_8888);
            cacheCanvas = new Canvas(cachebBitmap);
            cacheCanvas.drawColor(Color.TRANSPARENT);
        }

        public void clear() {
            flag = "0";
            if (cacheCanvas != null) {
                paint.setColor(Color.parseColor("#FBFBFB"));
                cacheCanvas.drawPaint(paint);
                paint.setColor(Color.BLACK);
                cacheCanvas.drawColor(Color.TRANSPARENT);
                invalidate();
            }
        }

        @Override
        protected void onDraw(Canvas canvas) {
            canvas.drawBitmap(cachebBitmap, 0, 0, null);
            canvas.drawPath(path, paint);
        }

        @Override
        protected void onSizeChanged(int w, int h, int oldw, int oldh) {

            int curW = cachebBitmap != null ? cachebBitmap.getWidth() : 0;
            int curH = cachebBitmap != null ? cachebBitmap.getHeight() : 0;
            if (curW >= w && curH >= h) {
                return;
            }
            if (curW < w)
                curW = w;
            if (curH < h)
                curH = h;

            Bitmap newBitmap = Bitmap.createBitmap(curW, curH, Bitmap.Config.ARGB_8888);
            Canvas newCanvas = new Canvas();
            newCanvas.setBitmap(newBitmap);
            if (cachebBitmap != null) {
                newCanvas.drawBitmap(cachebBitmap, 0, 0, null);
            }
            cachebBitmap = newBitmap;
            cacheCanvas = newCanvas;

        }

        private float cur_x, cur_y;

        @Override
        public boolean onTouchEvent(MotionEvent event) {

            float x = event.getX();
            float y = event.getY();

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN: {
                    cur_x = x;
                    cur_y = y;
                    path.moveTo(cur_x, cur_y);
                    break;
                }
                case MotionEvent.ACTION_MOVE: {
                    flag = "1";
                    path.quadTo(cur_x, cur_y, x, y);
                    cur_x = x;
                    cur_y = y;
                    break;
                }
                case MotionEvent.ACTION_UP: {
                    cacheCanvas.drawPath(path, paint);
                    path.reset();
                    break;
                }
            }
            invalidate();
            return true;
        }
    }

    @OnClick({R.id.iv_back, R.id.btn_cx_sign, R.id.btn_ok_sign})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.btn_cx_sign:
                // 重新签名
                mView.clear();
                break;
            case R.id.btn_ok_sign:
                if ("1".equals(flag)) {
                    dialog.show();
                    btnOkSign.setEnabled(false);
                    // 保存签名图片
                    savePhotoToSDCard();
                } else {
                    // 带回需要的数据
                    ToastUtils.showShortToast(QianMingActivity.this, "请确认签名");
                }
                break;
        }
    }

    public void savePhotoToSDCard() {
        // 获取签名图片
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = mView.getCachebBitmap();
                // 如果保存的图片为黑色的话,先设置背景为白色
                Bitmap outBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
                Canvas canvas = new Canvas(outBitmap);
                canvas.drawColor(Color.WHITE);
                canvas.drawBitmap(bitmap, 0, 0, null);

                path = Environment.getExternalStorageDirectory() + "/djlmapp_signphotos";
                File parentFile = new File(path);
                parentFile.mkdirs();
                File file = ImageTools.savePhotoToSDCard(outBitmap, path, "/sign.png");
                Log.e("项目异常", "------photoFile------" + file.getPath());
                imageUpload(file);
            }
        }).start();
    }

    /**
     * 上传图片
     */
    private void imageUpload(File file) {
        if (TextUtils.isEmpty(homeUrl)) {
            homeUrl = GlobalUrls.SIGN_TRUE;
        }
        MyApplication.getInstance().getHttpTools().getSingPhoto(homeUrl, file, new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    parseJson(response.body());
                } catch (Exception e) {
                    Log.e("项目异常", "------数据解析异常------" + e.toString());
                    ToastUtils.showShortToast(QianMingActivity.this, "数据解析异常");
                }

            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                Toast.makeText(QianMingActivity.this,
                        "网络或服务器错误", Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onFinish() {
                super.onFinish();
                if (dialog != null) {
                    dialog.dismiss();
                }
                btnOkSign.setEnabled(true);
            }
        });
    }

    private void parseJson(String json) {
        Gson gson = new Gson();
        SignImageInfo imageInfo = gson.fromJson(json, SignImageInfo.class);

        if (imageInfo.getCode() < 1000) {
            if (dialog != null) {
                dialog.dismiss();
            }
            // 带回需要的数据
            Intent intent = new Intent();
            intent.putExtra(UPLOAD_IMG_SUCCESS_RESULT_DATA, json);
            intent.putExtra("fileName", imageInfo.getFilename()); // 图片路径
            intent.putExtra("signFlag", flag); // 签名是否成功
            intent.putExtra("signMoney", imageInfo.getMoney()); // 钱
            setResult(2, intent);
            finish();
        } else {
            ToastUtils.showShortToast(QianMingActivity.this, imageInfo.getMsg());
        }
        if (path != null && !TextUtils.isEmpty(path)) {
            // 图片上传成功之后清空存储的图片
            ImageTools.deleteAllPhoto(QianMingActivity.this, path);
        }
    }

    /**
     * 沉浸式状态栏初始化
     */
    private void initImmersionBar() {
        ImmersionBar.with(this)
                .keyboardEnable(true)
                .navigationBarWithKitkatEnable(false)
                .statusBarDarkFont(true)
                .fitsSystemWindows(true)  //使用该属性,必须指定状态栏颜色;
                .statusBarColor(R.color.homeWhite)
                .init();
    }

    @Override
    protected void onResume() {
        /**
         * 设置为横屏
         */
        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        super.onResume();
    }


    //设置android app 的字体大小不受系统字体大小改变的影响
    @Override
    public Resources getResources() {
        Resources res = null;
        try {
            res = super.getResources();
            Configuration config = new Configuration();
            config.setToDefaults();
            res.updateConfiguration(config, res.getDisplayMetrics());
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("项目异常", "--onLivenessSuccess----getResources------" + e.toString());
        }
        return res;
    }

    @Override
    protected void onDestroy() {
        ImmersionBar.with(this).destroy();
        super.onDestroy();
    }

    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void Needs() {
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        QianMingActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void OnShowRationale(final PermissionRequest request) {
        request.proceed();
        isFirst = false;
    }

    @OnPermissionDenied({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void Denied() {
        if (isFirst) {
            return;
        }
        new AlertDialog.Builder(this)
                .setMessage("请开启应用的存储权限")
                .setCancelable(false)
                .setNegativeButton("确定", (dialog1, which) -> finish()).show();
    }

    @OnNeverAskAgain({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void AskAgain() {
        if (isFirst) {
            return;
        }
        new AlertDialog.Builder(this)
                .setMessage("请开启应用的存储权限")
                .setCancelable(false)
                .setNegativeButton("确定", (dialog1, which) -> finish()).show();
    }

    private boolean isFirst = true;
}
